import axios from "axios";
export default {
  state: {
    //需要响应式功能的状态数据
    list: [],
  },
  getters: {
    //用于返回state中的数据(处理后的数据)，类似于computed
  },
  mutations: {
    //用于修改state中的数据——必需是同步修改(最新版也可以异步修改)
    setList(state, list) {
      state.list = list;
    },
    updateNum(state, obj) {
      let index = obj.index;
      let num = obj.num;
      state.list[index].num = num;
    },
  },
  actions: {
    // 用于修改state中的数据——可以是异步或同步修改
    getCart(context) {
      //根据uid查询到改用户购物车对应商品的{pid:xx,num:xx}数组 再根据pid循环生成多个promise对象
      let uid = sessionStorage.getItem("uid");
      if (!uid) {
        context.commit("setList",[])
        return;
      } else {
        let url = `/cart/getcart?uid=${uid}`;
        axios.get(url).then((res) => {
          console.log(res.data);
          for (var i = 0, arr = [], nums = []; i < res.data.length; i++) {
            console.log(res.data[i].num);
            nums.push(res.data[i].num);
            arr.push(
              new Promise((resolve, reject) => {
                axios
                  .get(`product/details?pid=${res.data[i].pid}`)
                  .then((result) => {
                    resolve(result.data);
                  });
              })
            );
          }
          (async function(num) {
            await Promise.all([arr]).then((output) => {
              var arr = output[0];
              console.log(arr);
              for (var j = 0, Arr = []; j < arr.length; j++) {
                arr[j].then((v) => {
                  // console.log(nums);
                  // console.log(v);
                  Arr.push(v);
                  for (var k = 0; k < Arr.length; k++) {
                    Arr[k].num = nums[k];
                  }
                });
              }
              context.commit("setList", Arr);
            });
          })(nums);
        });
      }
    },
  },
};
